summaryrefslogtreecommitdiffstats
path: root/src/android/app/src/main/java/org/yuzu/yuzu_emu/utils/FileUtil.java
blob: 8665704cc450b14c06fcca77865a6fc25eff83cb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
package org.yuzu.yuzu_emu.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.DocumentsContract;

import androidx.annotation.Nullable;
import androidx.documentfile.provider.DocumentFile;

import org.yuzu.yuzu_emu.model.MinimalDocumentFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {
    static final String PATH_TREE = "tree";
    static final String DECODE_METHOD = "UTF-8";
    static final String APPLICATION_OCTET_STREAM = "application/octet-stream";
    static final String TEXT_PLAIN = "text/plain";

    /**
     * Create a file from directory with filename.
     * @param context Application context
     * @param directory parent path for file.
     * @param filename file display name.
     * @return boolean
     */
    @Nullable
    public static DocumentFile createFile(Context context, String directory, String filename) {
        try {
            Uri directoryUri = Uri.parse(directory);
            DocumentFile parent = DocumentFile.fromTreeUri(context, directoryUri);
            if (parent == null) return null;
            filename = URLDecoder.decode(filename, DECODE_METHOD);
            String mimeType = APPLICATION_OCTET_STREAM;
            if (filename.endsWith(".txt")) {
                mimeType = TEXT_PLAIN;
            }
            DocumentFile exists = parent.findFile(filename);
            if (exists != null) return exists;
            return parent.createFile(mimeType, filename);
        } catch (Exception e) {
            Log.error("[FileUtil]: Cannot create file, error: " + e.getMessage());
        }
        return null;
    }

    /**
     * Create a directory from directory with filename.
     * @param context Application context
     * @param directory parent path for directory.
     * @param directoryName directory display name.
     * @return boolean
     */
    @Nullable
    public static DocumentFile createDir(Context context, String directory, String directoryName) {
        try {
            Uri directoryUri = Uri.parse(directory);
            DocumentFile parent = DocumentFile.fromTreeUri(context, directoryUri);
            if (parent == null) return null;
            directoryName = URLDecoder.decode(directoryName, DECODE_METHOD);
            DocumentFile isExist = parent.findFile(directoryName);
            if (isExist != null) return isExist;
            return parent.createDirectory(directoryName);
        } catch (Exception e) {
            Log.error("[FileUtil]: Cannot create file, error: " + e.getMessage());
        }
        return null;
    }

    /**
     * Open content uri and return file descriptor to JNI.
     * @param context Application context
     * @param path Native content uri path
     * @param openmode will be one of "r", "r", "rw", "wa", "rwa"
     * @return file descriptor
     */
    public static int openContentUri(Context context, String path, String openmode) {
        try {
            Uri uri = Uri.parse(path);
            ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uri, openmode);
            if (parcelFileDescriptor == null) {
                Log.error("[FileUtil]: Cannot get the file descriptor from uri: " + path);
                return -1;
            }
            return parcelFileDescriptor.detachFd();
        }
        catch (Exception e) {
            Log.error("[FileUtil]: Cannot open content uri, error: " + e.getMessage());
        }
        return -1;
    }

    /**
     * Reference:  https://stackoverflow.com/questions/42186820/documentfile-is-very-slow
     * This function will be faster than DoucmentFile.listFiles
     * @param context Application context
     * @param uri Directory uri.
     * @return CheapDocument lists.
     */
    public static MinimalDocumentFile[] listFiles(Context context, Uri uri) {
        final ContentResolver resolver = context.getContentResolver();
        final String[] columns = new String[]{
                DocumentsContract.Document.COLUMN_DOCUMENT_ID,
                DocumentsContract.Document.COLUMN_DISPLAY_NAME,
                DocumentsContract.Document.COLUMN_MIME_TYPE,
        };
        Cursor c = null;
        final List<MinimalDocumentFile> results = new ArrayList<>();
        try {
            String docId;
            if (isRootTreeUri(uri)) {
                docId = DocumentsContract.getTreeDocumentId(uri);
            } else {
                docId = DocumentsContract.getDocumentId(uri);
            }
            final Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(uri, docId);
            c = resolver.query(childrenUri, columns, null, null, null);
            while(c.moveToNext()) {
                final String documentId = c.getString(0);
                final String documentName = c.getString(1);
                final String documentMimeType = c.getString(2);
                final Uri documentUri = DocumentsContract.buildDocumentUriUsingTree(uri, documentId);
                MinimalDocumentFile document = new MinimalDocumentFile(documentName, documentMimeType, documentUri);
                results.add(document);
            }
        } catch (Exception e) {
            Log.error("[FileUtil]: Cannot list file error: " + e.getMessage());
        } finally {
            closeQuietly(c);
        }
        return results.toArray(new MinimalDocumentFile[0]);
    }

    /**
     * Check whether given path exists.
     * @param path Native content uri path
     * @return bool
     */
    public static boolean Exists(Context context, String path) {
        Cursor c = null;
        try {
            Uri mUri = Uri.parse(path);
            final String[] columns = new String[] { DocumentsContract.Document.COLUMN_DOCUMENT_ID };
            c = context.getContentResolver().query(mUri, columns, null, null, null);
            return c.getCount() > 0;
        } catch (Exception e) {
            Log.info("[FileUtil] Cannot find file from given path, error: " + e.getMessage());
        } finally {
            closeQuietly(c);
        }
        return false;
    }

    /**
     * Check whether given path is a directory
     * @param path content uri path
     * @return bool
     */
    public static boolean isDirectory(Context context, String path) {
        final ContentResolver resolver = context.getContentResolver();
        final String[] columns = new String[] {
                DocumentsContract.Document.COLUMN_MIME_TYPE
        };
        boolean isDirectory = false;
        Cursor c = null;
        try {
            Uri mUri = Uri.parse(path);
            c = resolver.query(mUri, columns, null, null, null);
            c.moveToNext();
            final String mimeType = c.getString(0);
            isDirectory = mimeType.equals(DocumentsContract.Document.MIME_TYPE_DIR);
        } catch (Exception e) {
            Log.error("[FileUtil]: Cannot list files, error: " + e.getMessage());
        } finally {
            closeQuietly(c);
        }
        return isDirectory;
    }

    /**
     * Get file display name from given path
     * @param path content uri path
     * @return String display name
     */
    public static String getFilename(Context context, String path) {
        final ContentResolver resolver = context.getContentResolver();
        final String[] columns = new String[] {
                DocumentsContract.Document.COLUMN_DISPLAY_NAME
        };
        String filename = "";
        Cursor c = null;
        try {
            Uri mUri = Uri.parse(path);
            c = resolver.query(mUri, columns, null, null, null);
            c.moveToNext();
            filename = c.getString(0);
        } catch (Exception e) {
            Log.error("[FileUtil]: Cannot get file size, error: " + e.getMessage());
        } finally {
            closeQuietly(c);
        }
        return filename;
    }

    public static String[] getFilesName(Context context, String path) {
        Uri uri = Uri.parse(path);
        List<String> files = new ArrayList<>();
        for (MinimalDocumentFile file: FileUtil.listFiles(context, uri)) {
            files.add(file.getFilename());
        }
        return files.toArray(new String[0]);
    }

    /**
     * Get file size from given path.
     * @param path content uri path
     * @return long file size
     */
    public static long getFileSize(Context context, String path) {
        final ContentResolver resolver = context.getContentResolver();
        final String[] columns = new String[] {
                DocumentsContract.Document.COLUMN_SIZE
        };
        long size = 0;
        Cursor c =null;
        try {
            Uri mUri = Uri.parse(path);
            c = resolver.query(mUri, columns, null, null, null);
            c.moveToNext();
            size = c.getLong(0);
        } catch (Exception e) {
            Log.error("[FileUtil]: Cannot get file size, error: " + e.getMessage());
        } finally {
            closeQuietly(c);
        }
        return size;
    }

    public static boolean copyUriToInternalStorage(Context context, Uri sourceUri, String destinationParentPath, String destinationFilename) {
        InputStream input = null;
        FileOutputStream output = null;
        try {
            input = context.getContentResolver().openInputStream(sourceUri);
            output = new FileOutputStream(destinationParentPath + "/" + destinationFilename);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = input.read(buffer)) != -1) {
                output.write(buffer, 0, len);
            }
            output.flush();
            return true;
        } catch (Exception e) {
            Log.error("[FileUtil]: Cannot copy file, error: " + e.getMessage());
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    Log.error("[FileUtil]: Cannot close input file, error: " + e.getMessage());
                }
            }
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    Log.error("[FileUtil]: Cannot close output file, error: " + e.getMessage());
                }
            }
        }
        return false;
    }

    public static boolean isRootTreeUri(Uri uri) {
        final List<String> paths = uri.getPathSegments();
        return paths.size() == 2 && PATH_TREE.equals(paths.get(0));
    }

    public static void closeQuietly(AutoCloseable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (RuntimeException rethrown) {
                throw rethrown;
            } catch (Exception ignored) {
            }
        }
    }
}